<?php

namespace backend\models\form;

use backend\models\AdminUser;
use common\service\ConstatService;
use common\service\UtilService;
use Yii;
use yii\base\Model;
use common\service\BaseToolService ;
use backend\service\RbacService ;
use yii\helpers\FileHelper;

/**
 * Description of RegisterForm
 *
 * @author Administrator
 */
class RegisterForm extends Model {

    public $username;
    public $password;
    public $phone;
    public $role;
    public $status;
    public $avatar ;

    private $_user = false;

    /**
     * 验证输入框的信息
     */
    public function rules() {
        return [
            [['username','phone','role'],'required'] ,
            [['password'],'required', 'on'=>'add'] ,
            [['phone'], 'match','pattern' => '/^(0|86|17951)?(13[0-9]|15[012356789]|17[0-9]|18[0-9]|19[0-9]|14[57])[0-9]{8}$/ ','message' => '请输入正确的手机号码'],
            [['password'],'string'],
            [['password'], 'match','pattern' => '/^[a-zA-Z0-9\_\~\!\@\#\$\%\^\&\*\(\)\+\,\.\?]{6,20}$/','message' => '请输入6-20位字符.英文,数字,"~!@#$%^&*()_+,.?"的组合'],
            [['phone'], 'unique', 'targetClass' => '\backend\models\AdminUser', 'message' => '手机号已被使用', 'on'=>'add'],
            [['role'],'string'],
            [['role'],'validRole'],
            [['status'],'integer'],
            [['avatar'], 'file', 'skipOnEmpty' => true, 'extensions' => 'png,jpg,gif,jpeg'],
        ];
    }

    public function attributeLabels() {
        return [
            'username'=>'用户名',
            'password' => '登录密码' ,
            'phone' => '手机' ,
            'role' => '角色' ,
            'status' => '状态' ,
            'avatar' => '头像' ,
        ];
    }

    public function validRole(){
        if(empty($this->role)){
            $this->addError("role", "角色不能为空") ;
            return false ;
        }
    }

    public function addUser(){
        $roleTypeArr = ConstatService::ROLE_TO_TYPEID ;
        $typeId = empty($roleTypeArr[$this->role])?0:$roleTypeArr[$this->role] ;

        $user = new AdminUser() ;
        $order = BaseToolService::createOrder() ;
        $en_password = BaseToolService::encodePassword($order, $this->password);
        $user->type_id = empty($roleTypeArr[$this->role])?0:$roleTypeArr[$this->role] ; //后台用户 0-为其它类型 自定义角色时为0
        $user->password_order = $order;
        $user->username = $this->username ;
        $user->password = $en_password ;
        $user->phone = $this->phone;
        $user->role = $this->role;
        $user->create_user_id = Yii::$app->admin->identity->user_id;
        $user->status = $this->status;
        $user->uptime = time() ;

        $add_rs = $user->save();
        if(!empty($this->role)){
            RbacService::addUserAssignment($user->attributes['user_id'], $this->role);
        }
        if($add_rs==true){
            $userId = $user->user_id ;
            $webRoot = Yii::getAlias("@webroot") ;
            $basePath = "/uploads/avatar/" ;
            FileHelper::createDirectory($webRoot.$basePath) ;
            $hostName = Yii::$app->request->hostInfo;

            if(!empty($this->avatar)){
                $filename = $userId . '.' . $this->avatar->extension;
                $avatar  = $hostName . $basePath . $filename;
                $savePath = $webRoot . $basePath . $filename;
                $this->avatar->saveAs($savePath);
                AdminUser::updateAll(["avatar"=>$avatar],["user_id"=>$userId]) ;
            }

            return ["status"=>true,"msg"=>"添加用户成功","user_id"=>$user->user_id] ;
        }else{
            return ["status"=>false,"msg"=>"添加用户失败"] ;
        }
    }

    /**
     * 修改用户
     * @param $user_id
     * @return array
     */
    public function editUser($user_id)
    {
        $user = AdminUser::findOne(["user_id" => $user_id]);
        if (empty($user)) {
            return ["status" => false, "msg" => "无此用户"];
        }

        $phone_rs = AdminUser::find()->where(['phone' => $this->phone])->andWhere(['!=', 'user_id', $user_id])->exists();
        if ($phone_rs) {
            return ["status"=>false,"msg"=>"手机号已被使用"] ;
        }

        $roleTypeArr = ConstatService::ROLE_TO_TYPEID ;

        RbacService::editUserAssignment($user_id, $this->role, $user->role);

        $user->type_id = empty($roleTypeArr[$this->role])?0:$roleTypeArr[$this->role] ; //后台用户 0-为其它类型 自定义角色时为0
        $user->username = $this->username ;
        $user->phone = $this->phone;
        $user->role = $this->role;
        $user->status = $this->status;
        $user->uptime = time() ;
        if(!empty($this->password)){
            $user->password = BaseToolService::encodePassword($user->password_order, $this->password);
        }

        $webRoot = Yii::getAlias("@webroot") ;
        $basePath = "/uploads/avatar/" ;
        FileHelper::createDirectory($webRoot.$basePath) ;
        $hostName = Yii::$app->request->hostInfo;

        if(!empty($this->avatar)){
            $userId = $user->user_id ;
            $filename = $userId . '.' . $this->avatar->extension;
            $avatar  = $hostName . $basePath . $filename;
            $savePath = $webRoot . $basePath . $filename;
            $this->avatar->saveAs($savePath);
            $user->avatar = $avatar ;
        }

        $add_rs = $user->save() ;
        if(!empty($this->role)){
            RbacService::addUserAssignment($user->attributes['user_id'], $this->role);
        }
        if($add_rs==true){
            return ["status"=>true,"msg"=>"编辑成功"] ;
        }else{
            return ["status"=>false,"msg"=>"编辑失败"] ;
        }
    }

    private function getUser(){
        if ($this->_user === false) {
            $this->_user = AdminUser::findOne(["phone"=>$this->phone]) ;
        }
        return $this->_user;
    }

}
